<template>
  <view class="order-detail-container">
    <!-- 状态头部 -->
    <view class="status-header">
      <view class="status-icon">
        <uv-icon name="clock" color="#FF6B35" size="48" />
      </view>
      <view class="status-info">
        <text class="status-text">待付款</text>
        <text class="payment-timer">请在{{ paymentTimer }}内完成付款</text>
      </view>
    </view>


    <view class="info-card">
      <view class="user-info">
        <view class="avatar">
          <uv-avatar :src="userInfo.avatar"></uv-avatar>
        </view>
        <view class="user-details">
          <text class="user-name">{{ orderInfo.userName }}</text>
          <text class="user-phone">{{ orderInfo.userPhone }}</text>
        </view>
        <view class="license-plate">
          <text class="plate-text">{{ orderInfo.licensePlate }}</text>
        </view>
      </view>
    </view>

    <!-- 派送地址卡片 -->
    <view class="info-card">
      <view class="address-info">
        <view class="address-icon">
          <uv-icon name="map-fill" :size="24" :color="'#FF6B35'" />
        </view>
        <view class="address-details">
          <view class="address-label">派送地址</view>
          <view class="address-text">{{ orderInfo.deliveryAddress }}</view>
        </view>
      </view>
    </view>

    <!-- 产品信息卡片 -->
    <view class="info-card">
      <view class="product-info">
        <view class="product-icon">
          <view class="oil-badge">
            <image :src="orderInfo.goods_image" mode="aspectFill" style="width: 100%; height: 100%;" />
          </view>
        </view>
        <view class="product-details">
          <text class="product-name">{{ orderInfo.productName }}</text>
          <text class="product-quantity">用油量: {{ orderInfo.quantity }}升</text>
        </view>
        <view class="product-price">
          <text class="price-symbol">¥</text>
          <text class="price-amount">{{ orderInfo.goods_money }}</text>
        </view>
      </view>
    </view>

    <!-- 订单信息卡片 -->
    <view class="info-card">
      <view class="order-details">
        <view class="detail-item">
          <text class="detail-label">下单时间:</text>
          <text class="detail-value">{{ orderInfo.orderTime }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">用油时间:</text>
          <text class="detail-value">{{ orderInfo.usageTime }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">下单方式:</text>
          <text class="detail-value">{{ orderInfo.paymentMethod == 'remaining' ? '余量下单' : '余额下单' }}</text>
        </view>
      </view>
    </view>

    <!-- 实际用量和金额 -->
    <view class="info-card">
      <view class="actual-info">
        <view class="actual-item">
          <text class="actual-label">实际用油量:</text>
          <text class="actual-value">{{ orderInfo.actualQuantity }}升</text>
        </view>
        <view class="actual-item">
          <text class="actual-label">实际金额:</text>
          <text class="actual-value">{{ orderInfo.order_price }}元</text>
        </view>
      </view>
    </view>

    <!-- 凭证信息 -->
    <view class="info-card">
      <view class="voucher-info">
        <text class="voucher-title">凭证信息</text>
        <view class="voucher-images">
          <view v-for="(voucher, index) in orderInfo.voucher" :key="index" class="voucher-image">
            <image :src="voucher" mode="aspectFill" />
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <view class="payment-section">
        <view class="payment-info">
          <text class="payment-label">实际金额:</text>
          <text class="payment-amount">¥{{ orderInfo.order_price }}</text>
        </view>
        <view class="payment-button">
          <uv-button text="去付款" size="large" :color="'#FF6B35'"
            customStyle="width: 200rpx; height: 88rpx; border-radius: 44rpx;" @click="goToPayment" />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { UserInfoManager } from '@/utils/userInfo'
import { formatDateTime } from '@/utils/dateTime'
import { useRequest } from '@/api'
const userInfo = UserInfoManager.getUserInfo()
const { API_JIDAN_DETAIL_GET } = useRequest()

// 路由参数
const orderId = ref('')
const loading = ref(false)

// 订单信息类型定义
interface OrderInfo {
  userName: string
  userPhone: string
  licensePlate: string
  deliveryAddress: string
  goods_image: string
  productName: string
  quantity: number
  goods_money: string
  orderTime: string
  usageTime: string
  paymentMethod: string
  actualQuantity: number
  order_price: string
  voucher: string[]
  order_type: string
}

// 订单信息
const orderInfo = ref<OrderInfo>({
  userName: '',
  userPhone: '',
  licensePlate: '',
  deliveryAddress: '',
  goods_image: '',
  productName: '',
  quantity: 1,
  goods_money: '',
  orderTime: '',
  usageTime: '',
  paymentMethod: '',
  actualQuantity: 0,
  order_price: '',
  voucher: [],
  order_type: ''
})

// 付款倒计时
const paymentTimer = ref('23:59:59')
let timerInterval: any = null

// 去付款
const goToPayment = () => {
  if(orderInfo.value.order_type == 'balance'){
    uni.navigateTo({ url: '/user/order/detailPay1?id=' + orderId.value + '&type=1' })
  }else{
    uni.navigateTo({ url: '/user/order/detailPay2?id=' + orderId.value + '&type=1' })
  }
}

// 开始付款倒计时
const startPaymentTimer = () => {
  let totalSeconds = 24 * 60 * 60 // 24小时
  timerInterval = setInterval(() => {
    totalSeconds--
    if (totalSeconds <= 0) {
      stopPaymentTimer()
      uni.showToast({
        title: '付款时间已过期',
        icon: 'none'
      })
      return
    }

    const hours = Math.floor(totalSeconds / 3600)
    const minutes = Math.floor((totalSeconds % 3600) / 60)
    const seconds = totalSeconds % 60

    paymentTimer.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  }, 1000)
}

// 停止付款倒计时
const stopPaymentTimer = () => {
  if (timerInterval) {
    clearInterval(timerInterval)
    timerInterval = null
  }
}

const getOrderDetail = async () => {
  if (!orderId.value) {
    uni.showToast({
      title: '订单ID不能为空',
      icon: 'none'
    })
    return
  }

  loading.value = true
  try {
    const params = {
      id: orderId.value,
      isdriver: UserInfoManager.lastrole()
    }
    const res = await API_JIDAN_DETAIL_GET(params)
    if (res.code === 1) {
      const rawVouchers = (res.data && (res.data.vouchers ?? res.data.voucher)) || []
      const voucherUrls = Array.isArray(rawVouchers)
        ? rawVouchers.filter((u: any) => typeof u === 'string' && u)
        : (typeof rawVouchers === 'string' && rawVouchers)
          ? rawVouchers.split(',').map((s: string) => s.trim()).filter(Boolean)
          : []
      orderInfo.value = {
        userName: res.data.username || '',
        userPhone: res.data.mobile || '',
        licensePlate: res.data.carnumber || '',
        deliveryAddress: res.data.address_detail || '',
        goods_image: res.data.goods_image || '',
        productName: res.data.goods_name || '-',
        quantity: res.data.usage || 1,
        goods_money: res.data.goods_money || '',
        orderTime: formatDateTime(res.data.order_time) || '2023.10.10 12:00',
        usageTime: formatDateTime(res.data.use_time) || '2023.10.10 12:00',
        paymentMethod: res.data.order_type || '余额下单',
        actualQuantity: res.data.real_usage || 0,
        order_price: res.data.order_price || '',
        voucher: voucherUrls || [],
        order_type: res.data.order_type || ''
      }

      // 开始付款倒计时
      startPaymentTimer()
    }
  } catch (error) {
    
  } finally {
    loading.value = false
  }
}

// 统一通过 onLoad 获取路由参数，兼容 APP/H5/小程序
onLoad((options: Record<string, any>) => {
  const id = options?.id
  if (id) {
    try { orderId.value = decodeURIComponent(String(id)) } catch { orderId.value = String(id) }
    getOrderDetail()
  }
})

onUnmounted(() => {
  stopPaymentTimer()
})
</script>

<style lang="scss" scoped>
.order-detail-container {
  min-height: 100vh;
  background: #f6f7f9;
  padding: 20rpx;
  padding-bottom: 120rpx;
}

/* 状态头部 */
.status-header {
  display: flex;
  align-items: center;
  padding: 32rpx 24rpx;
  background: linear-gradient(to bottom, #fff4e8, #fffefd);
  margin-bottom: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

  .status-icon {
    margin-right: 24rpx;
  }

  .status-info {
    flex: 1;

    .status-text {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }

    .payment-timer {
      font-size: 26rpx;
      color: #FF6B35;
      margin-top: 8rpx;
    }
  }
}

/* 信息卡片 */
.info-card {
  background: #fff;
  margin-bottom: 20rpx;
  padding: 32rpx 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

  .address-info {
    display: flex;
    align-items: flex-start;

    .address-icon {
      margin-right: 24rpx;
      margin-top: 4rpx;
    }

    .address-details {
      flex: 1;

      .address-label {
       
        margin-bottom: 12rpx;
      }

      .address-text {
        font-size: 28rpx;
        color: #333;
        font-weight: 600;
        line-height: 36rpx;
      }
    }
  }

  .product-info {
    display: flex;
    align-items: center;

    .product-icon {
      margin-right: 24rpx;

      .oil-badge {
        width: 80rpx;
        height: 80rpx;
        background: #fff3ed;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        .oil-type {
          font-size: 24rpx;
          font-weight: 600;
          color: #333;
          margin-top: 4rpx;
        }
      }
    }

    .product-details {
      flex: 1;

      .product-name {
        display: block;
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }

      .product-quantity {
        font-size: 26rpx;
        color: #666;
      }
    }

    .product-price {
      text-align: right;

      .price-symbol {
        font-size: 28rpx;
        color: #FF6B35;
      }

      .price-amount {
        font-size: 36rpx;
        font-weight: 600;
        color: #FF6B35;
      }
    }
  }

  .order-details {
    .detail-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .detail-label {
        font-size: 26rpx;
        color: #666;
      }

      .detail-value {
        font-size: 26rpx;
        color: #333;
      }
    }
  }

  .actual-info {
    .actual-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .actual-label {
        font-size: 26rpx;
        color: #666;
      }

      .actual-value {
        font-size: 26rpx;
        color: #333;
        font-weight: 600;
      }
    }
  }

  .voucher-info {
    .voucher-title {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
    }

    .voucher-images {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;

      .voucher-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
        overflow: hidden;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}

/* 底部操作区域 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 40rpx;
  border-top: 1rpx solid #f0f0f0;
  z-index: 999;

  .payment-section {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .payment-info {
      .payment-label {
        font-size: 26rpx;
        color: #666;
      }

      .payment-amount {
        font-size: 32rpx;
        font-weight: 600;
        color: #FF6B35;
        margin-left: 8rpx;
      }
    }

    .payment-button {
      flex-shrink: 0;
    }
  }
}

.user-info {
  display: flex;
  align-items: center;

  .avatar {
    margin-right: 24rpx;
  }

  .user-details {
    flex: 1;

    .user-name {
      display: block;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 8rpx;
    }

    .user-phone {
      font-size: 26rpx;
      color: #666;
    }
  }

  .license-plate {
    .plate-text {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
}
</style>